/**
 * @version 1.0
 * @author Ha Giang
 * @date
 */
package DiscoveryFunction;

import Communications.*;
import java.util.*;

/**
 * This class servers as a client
 *
 */
public class Client {

    Multicast mc = new Multicast();
    UnicastClient uc = null;
    Queue multicastStream;
    ArrayList<ServiceInfo> si = new ArrayList();
    List notifyInputStream = null;

    /**
     * Query services
     */
    public void query() {

        //start Unicast Server to get response
        NotifyServer ns = new NotifyServer();
        ns.start();
        notifyInputStream = ns.getMessagesStream();

        //start multicast client channel
        multicastStream = mc.startMulticastClientChannel();

        // send "Query" command + it's IP
        mc.announceMsgToClientChannel("Query:" + ns.getIp());
        // get response
        int size = new Integer(ns.getMessage());
        for (int i = 0; i < size; i++) {
            String s = ns.getMessage();
            ServiceInfo t = new ServiceInfo();
            t.loadString(s);
            si.add(t);
        }
    }

    /**
     * Connect to a service
     *
     * @param service The service
     * @param attempts number of attempts
     * @return successful/failed
     */
    public int connectToService(ServiceInfo service, int attempts) {
        //TODO: add attemption
        uc = new UnicastClient(service.getIp(), service.getPort());
        return 1;//successful
        //0: unsuccesful
    }

    public ArrayList<ServiceInfo> getServiceInfo() {
        return si;
    }
}
